package com.stx.jeepay.payment.controller.transfer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.entity.MchAppEntity;
import com.stx.jeepay.core.entity.MchInfoEntity;
import com.stx.jeepay.core.entity.TransferOrderEntity;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.PayInterfaceConfigService;
import com.stx.jeepay.core.service.TransferOrderService;
import com.stx.jeepay.core.utils.SeqKit;
import com.stx.jeepay.core.utils.SpringBeansUtil;
import com.stx.jeepay.core.utils.StringKit;
import com.stx.jeepay.payment.channel.ITransferService;
import com.stx.jeepay.payment.controller.ApiController;
import com.stx.jeepay.payment.exception.ChannelException;
import com.stx.jeepay.payment.model.MchAppConfigContext;
import com.stx.jeepay.payment.rqrs.msg.ChannelRetMsg;
import com.stx.jeepay.payment.rqrs.transfer.TransferOrderRQ;
import com.stx.jeepay.payment.rqrs.transfer.TransferOrderRS;
import com.stx.jeepay.payment.service.ConfigContextQueryService;
import com.stx.jeepay.payment.service.PayMchNotifyService;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 转账接口
 */
@Slf4j
@RestController
public class TransferOrderController extends ApiController {

    @Autowired
    private ConfigContextQueryService configContextQueryService;
    @Autowired
    private TransferOrderService transferOrderService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private PayMchNotifyService payMchNotifyService;

    /**
     * 转账
     **/
    @PostMapping("/api/transferOrder")
    public ApiRes transferOrder() {
        TransferOrderEntity transferOrder = null;

        // 获取参数
        TransferOrderRQ bizRQ = getRQByWithMchSign(TransferOrderRQ.class);

        try {
            String mchNo = bizRQ.getMchNo();
            String appId = bizRQ.getAppId();
            String ifCode = bizRQ.getIfCode();

            // 商户订单号是否重复
            if (transferOrderService.count(new LambdaQueryWrapper<TransferOrderEntity>()
                    .eq(TransferOrderEntity::getMchNo, mchNo)
                    .eq(TransferOrderEntity::getMchOrderNo, bizRQ.getMchOrderNo())) > 0) {
                throw new BizException("商户订单[" + bizRQ.getMchOrderNo() + "]已存在");
            }

            if (StringUtils.isNotEmpty(bizRQ.getNotifyUrl()) && !StringKit.isAvailableUrl(bizRQ.getNotifyUrl())) {
                throw new BizException("异步通知地址协议仅支持http:// 或 https:// !");
            }

            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(mchNo, appId);
            if (mchAppConfigContext == null) {
                throw new BizException("获取商户应用信息失败");
            }

            MchAppEntity mchApp = mchAppConfigContext.getMchApp();
            MchInfoEntity mchInfo = mchAppConfigContext.getMchInfo();

            // 判断是否已正确配置
            if (!payInterfaceConfigService.mchAppHasAvailableIfCode(appId, ifCode)) {
                throw new BizException("应用未开通此接口配置!");
            }

            ITransferService transferService =
                    SpringBeansUtil.getBean(ifCode + "TransferService", ITransferService.class);
            if (transferService == null) {
                throw new BizException("无此转账通道接口");
            }

            if (!transferService.isSupport(bizRQ.getEntryType())) {
                throw new BizException("该接口不支持该入账方式");
            }

            transferOrder = genTransferOrder(bizRQ, mchInfo, mchApp, ifCode);

            // 前置校验
            String errMsg = transferService.preCheck(bizRQ, transferOrder);
            if (StringUtils.isNotEmpty(errMsg)) {
                throw new BizException(errMsg);
            }

            // 入库
            transferOrderService.save(transferOrder);

            // 调用上游的支付宝或者微信的支付接口
            ChannelRetMsg channelRetMsg = transferService.transfer(bizRQ, transferOrder, mchAppConfigContext);

            //处理退款状态
            this.processChannelMsg(channelRetMsg, transferOrder);

            TransferOrderRS bizRS = TransferOrderRS.buildByRecord(transferOrder);
            return ApiRes.okWithSign(bizRS, mchApp.getAppSecret());
        } catch (BizException e) {
            return ApiRes.customFail(e.getMessage());
        } catch (ChannelException e) {
            //处理上游返回数据
            this.processChannelMsg(e.getChannelRetMsg(), transferOrder);

            if (e.getChannelRetMsg().getChannelState() == ChannelRetMsg.ChannelState.SYS_ERROR) {
                return ApiRes.customFail(e.getMessage());
            }

            TransferOrderRS bizRes = TransferOrderRS.buildByRecord(transferOrder);
            return ApiRes.okWithSign(bizRes, configContextQueryService.queryMchApp(bizRQ.getMchNo(), bizRQ.getAppId()).getAppSecret());
        } catch (Exception e) {
            log.error("系统异常：{}", e);
            return ApiRes.customFail("系统异常");
        }
    }

    /**
     * 处理返回的渠道信息，并更新订单状态
     * TransferOrder将对部分信息进行 赋值操作。
     **/
    private void processChannelMsg(ChannelRetMsg channelRetMsg, TransferOrderEntity transferOrder) {
        //对象为空 || 上游返回状态为空， 则无需操作
        if (channelRetMsg == null || channelRetMsg.getChannelState() == null) {
            return;
        }

        String transferId = transferOrder.getTransferId();

        // 明确成功
        if (ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == channelRetMsg.getChannelState()) {
            this.updateInitOrderStateThrowException(TransferOrderEntity.STATE_SUCCESS, transferOrder, channelRetMsg);
            payMchNotifyService.transferOrderNotify(transferOrder);
        } else if (ChannelRetMsg.ChannelState.CONFIRM_FAIL == channelRetMsg.getChannelState()) {
            // 明确失败
            this.updateInitOrderStateThrowException(TransferOrderEntity.STATE_FAIL, transferOrder, channelRetMsg);
            payMchNotifyService.transferOrderNotify(transferOrder);
        } else if (ChannelRetMsg.ChannelState.WAITING == channelRetMsg.getChannelState() ||
                ChannelRetMsg.ChannelState.UNKNOWN == channelRetMsg.getChannelState() ||
                ChannelRetMsg.ChannelState.API_RET_ERROR == channelRetMsg.getChannelState()
        ) {
            this.updateInitOrderStateThrowException(TransferOrderEntity.STATE_ING, transferOrder, channelRetMsg);

            // 系统异常：  订单不再处理。  为： 生成状态
        } else if (ChannelRetMsg.ChannelState.SYS_ERROR == channelRetMsg.getChannelState()) {

        } else {
            throw new BizException("ChannelState 返回异常");
        }
    }

    /**
     * 更新订单状态 --》 订单生成--》 其他状态  (向外抛出异常)
     **/
    private void updateInitOrderStateThrowException(byte orderState, TransferOrderEntity transferOrder, ChannelRetMsg channelRetMsg) {
        transferOrder.setState(orderState);
        transferOrder.setChannelOrderNo(channelRetMsg.getChannelOrderId());
        transferOrder.setErrCode(channelRetMsg.getChannelErrCode());
        transferOrder.setErrMsg(channelRetMsg.getChannelErrMsg());

        boolean isSuccess = transferOrderService.updateInit2Ing(transferOrder.getTransferId());

        if (!isSuccess) {
            throw new BizException("更新转账订单异常");
        }

        isSuccess = transferOrderService.updateIng2SuccessOrFail(transferOrder.getTransferId(), transferOrder.getState(),
                channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg());

        if (!isSuccess) {
            throw new BizException("更新转账订单异常");
        }
    }


    private TransferOrderEntity genTransferOrder(TransferOrderRQ rq, MchInfoEntity mchInfo, MchAppEntity mchApp, String ifCode) {
        TransferOrderEntity transferOrder = new TransferOrderEntity();
        transferOrder.setTransferId(SeqKit.genTransferId()); //生成转账订单号
        transferOrder.setMchNo(mchInfo.getMchNo()); //商户号
        transferOrder.setIsvNo(mchInfo.getIsvNo()); //服务商号
        transferOrder.setAppId(mchApp.getAppId()); //商户应用appId
        transferOrder.setMchName(mchInfo.getMchShortName()); //商户名称（简称）
        transferOrder.setMchType(mchInfo.getType()); //商户类型
        transferOrder.setMchOrderNo(rq.getMchOrderNo()); //商户订单号
        transferOrder.setIfCode(ifCode); //接口代码
        transferOrder.setEntryType(rq.getEntryType()); //入账方式
        transferOrder.setAmount(rq.getAmount()); //订单金额
        transferOrder.setCurrency(rq.getCurrency()); //币种
        transferOrder.setClientIp(StringUtils.defaultIfEmpty(rq.getClientIp(), getClientIp())); //客户端IP
        transferOrder.setState(TransferOrderEntity.STATE_INIT); //订单状态, 默认订单生成状态
        transferOrder.setAccountNo(rq.getAccountNo()); //收款账号
        transferOrder.setAccountName(rq.getAccountName()); //账户姓名
        transferOrder.setBankName(rq.getBankName()); //银行名称
        transferOrder.setTransferDesc(rq.getTransferDesc()); //转账备注
        transferOrder.setExtParam(rq.getExtParam()); //商户扩展参数
        transferOrder.setNotifyUrl(rq.getNotifyUrl()); //异步通知地址
        transferOrder.setCreatedAt(new Date()); //订单创建时间
        return transferOrder;
    }
}
